##
## This file is part of the django-oidauth project.
##
## Copyright (C) 2009 Filippo Santovito <http://mementomori.myvidoop.com/>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License version 3 as
## published by the Free Software Foundation;
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
##

from django.contrib.auth.models import User
from oidauth.models import OpenID

class OpenIDBackend():
    def authenticate(self, openid_url=None):
        """
        an OpenID user doesn't need a local password.
        It suffices he is listed in the user table.

        a valid OpenID user has a valid openid_set RelatedManager
        so we'll check the user.username is equal to user.get_profile().url
        """
        user = None
        try:
            user = User.objects.get(username=openid_url)
        except User.DoesNotExist:
            print "be: user not exists"
            return None

        try:
            user.get_profile()
        except OpenID.DoesNotExist:
            print "be: openid not exists"
            return None
        
        if user.username == user.get_profile().url:
            return user
        else:
            print "be: %s <> %s" % (user.username, user.get_profile().url)
            return None
        
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
     
